<template>
  <div  class="p-2">
    <el-row :gutter="10">
      <el-col :lg="4" :xs="24" style="">
        <el-card shadow="hover">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <div><p style="font-weight: 400;">任务类型</p></div>
            <div>          <el-button type="primary" plain icon="Plus" @click="UpdateTypeDialogShow" v-hasPermi="['attendance:shift:add']">新增</el-button>
            </div>
          </div>
              <el-tree
            class="mt-2"
            ref="deptTreeRef"
            node-key="typeId"
            :data="groupOptions"
            :props="{ label: 'typeName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-contextmenu.prevent="openContextMenu"
        
          />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div class="search" v-show="showSearch">
            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="queryParams.taskName"  placeholder="请输入名称" clearable style="width: 240px"  />
          </el-form-item>
          <el-form-item label="任务状态" prop="taskStatus">
            <!-- <el-select v-model="queryParams.catalogueId" placeholder="请选择计划" clearable>
              <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select> -->
            <el-select  v-model="queryParams.taskStatus" placeholder="请选择">
    <el-option
      v-for="item in taskStausArr"
      :key="item.id"
      :label="item.label"
      :value="item.id">
    </el-option>
  </el-select>
          </el-form-item>
          <el-form-item label="任务类型" prop="typeId">
            <el-select     v-model="queryParams.typeId" placeholder="请选择">
    <el-option
      v-for="item in groupOptions"
      :key="item.typeId"
      :label="item.typeName"
      :value="item.typeId">
    </el-option>
  </el-select>
            <!-- <el-select v-model="queryParams.isScore" placeholder="请选择计划" clearable>
              <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select> -->
          </el-form-item>
          <el-form-item label="执行人" prop="executor">
            <el-input v-model="queryParams.executor"  placeholder="请输入名称" clearable style="width: 240px"  />
          </el-form-item>
          <el-form-item label="发起人" prop="createByName">
            <el-input v-model="queryParams.createByName"  placeholder="请输入名称" clearable style="width: 240px"  />
          </el-form-item>
          <!-- <el-form-item label="发布时段" prop="time">
            <el-input v-model="queryParams.itemsName"  placeholder="请输入名称" clearable style="width: 240px"  />
          </el-form-item> -->
          <el-form-item label="时间范围" prop="belongId">
            <el-tree-select
                v-model="queryParams.belongId"
                :data="classOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择"
                check-strictly
                default-expand-all
                @change="timeTypeonchange"
            />
          </el-form-item>
          <el-form-item label="日期" style="width: 308px">
            <el-date-picker
              v-model="dateRangeCreateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:group:add']">新增</el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="multiple" @click="handleUpdateGroup()" v-hasPermi="['attendance:group:edit']"
                  >修改</el-button
                >
              </el-col> -->
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['attendance:group:remove']"
                  >删除</el-button
                >
              </el-col> 
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:group:export']">导出</el-button>
              </el-col> 
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table
            height="calc(100vh - 370px)"
            v-loading="loading"
            :data="groupList"
            @selection-change="handleSelectionChange"
             :row-key="(row) => row.taskId "
            @row-dblclick="(row: any, column: any, event: Event) => handleUpdateGroup(row)"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="任务编号" align="center" prop="taskId" />
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="任务类型" align="center" prop="typeId" >
          
          </el-table-column>
        <el-table-column label="任务状态" align="center" prop="taskStatus">
          <template  #default="scope">
            <span v-if="scope.row.taskStatus=='0'">
            处理中
          </span>
          <span v-if="scope.row.taskStatus=='1'">
            已取消
          </span>
          <span v-if="scope.row.taskStatus=='2'">
            已完成
          </span>
          <span v-if="scope.row.taskStatus=='3'">
            超时待办
          </span>
          <span v-if="scope.row.taskStatus=='' || scope.row.taskStatus==null">
            全部
          </span>
        </template>
          </el-table-column>
        <el-table-column label="执行人" align="center" prop="executor" />
        <el-table-column label="发起人" align="center" prop="createByName" />
        <el-table-column label="发布时间" align="center" prop="createTime" />
        <el-table-column label="完成时间" align="center" prop="askCompleteTime" />
        <el-table-column label="巡检记录单号" align="center" prop="patrolId" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdateGroup(scope.row)"
                             v-hasPermi="['attendance:group:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['attendance:group:remove']"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
  
          </el-table>
          <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>
    <div v-show="showMenu" class="custom-menu">
      <ul>
        <li @click="menuItemAdd">添加子类型</li>
        <li @click="menuItemUpdate">编辑</li>
        <li @click="menuItemDelete" v-show="!currentNodeData.children">删除</li>
        <li @click="menuHide">取消</li>
      </ul>
    </div>
     <!-- 添加或修改学生识别记录对话框 -->
     <el-dialog :title="dialog.title" v-model="dialog.visible"  append-to-body>
      <el-form ref="studentRecognitionRecordFormRef" :model="form" :rules="rules" label-position="right" label-width="120px">
    <el-form-item label="任务名称" prop="taskName">
      <el-input v-model="form.taskName" placeholder="请输入任务名称" />
    </el-form-item>
    <el-form-item label="执行人" prop="executor">
      <el-select multiple v-model="form.executor" placeholder="请选择执行人">
    <el-option
      v-for="item in todolist"
      :key="item.userId"
      :label="item?.dept?(item?.dept?.deptName+'--'+item.nickName):item.nickName"
      :value="item.nickName">
    </el-option>
  </el-select>
      <!-- <el-input v-model="form.studentName" placeholder="请输入学生姓名" /> -->
    </el-form-item>
    <el-form-item label="任务类型" prop="typeId">
      <el-select v-model="form.typeId" placeholder="请选择">
    <el-option
      v-for="item in groupOptions"
      :key="item.typeId"
      :label="item.typeName"
      :value="item.typeId">
    </el-option>
  </el-select>
    </el-form-item>
    <el-form-item label="要求完成时间" prop="askCompleteTime">
      <el-date-picker
      v-model="form.askCompleteTime"
      type="datetime"
      placeholder="选择日期时间">
    </el-date-picker>
    </el-form-item>
    <el-form-item label="任务内容" prop="remark">
      <el-input type="textarea" v-model="form.remark" placeholder="请输入班级名称" />
    </el-form-item>
    <el-form-item label="上传图片" prop="imgList">
      <image-upload v-model="form.imgList" :isShowTip="false"  :verifyWay="1" />
    </el-form-item>
    </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 巡检任务详情 -->
    <el-dialog :title="detaildialog.title" v-model="detaildialog.visible"  append-to-body>
      <el-form ref="ddetailRecordFormRef" :model="detailform" :rules="rules" label-position="right" label-width="120px">
    <el-form-item label="任务名称" prop="taskName">
      <el-input disabled="true" v-model="detailform.taskName" placeholder="请输入任务名称" />
    </el-form-item>
    <el-form-item label="执行人" prop="executor">
        <el-input disabled="true" v-model="detailform.executor" placeholder="请输入任务名称" />
      <!-- <el-input v-model="form.studentName" placeholder="请输入学生姓名" /> -->
    </el-form-item>
    <el-form-item label="要求完成时间" prop="askCompleteTime">
      <el-date-picker
      disabled="true"
      v-model="detailform.askCompleteTime"
      type="datetime"
      placeholder="选择日期时间">
    </el-date-picker>
    </el-form-item>
    <el-form-item label="任务内容" prop="remark">
      <el-input :disabled="true" type="textarea" v-model="detailform.remark" placeholder="请输入班级名称" />
    </el-form-item>
    <el-form-item label="任务图片" prop="imgList">
      <el-image 
      v-for="item in detailform.imgList"
    style="width: 100px; height: 100px;margin-right: 20px;"
    :src="item" 
    :preview-src-list="detailform.imgList">
  </el-image>
    </el-form-item>
    <el-form-item label="任务类型" prop="typeId">
      <el-select disabled="true" v-model="detailform.typeId" placeholder="请选择">
    <el-option
      v-for="item in groupOptions"
      :key="item.typeId"
      :label="item.typeName"
      :value="item.typeId">
    </el-option>
  </el-select>
    </el-form-item>
    <el-form-item v-for="(item ,index) in detailform.taskViews" :label="'办理记录'+Number(index+1)" prop="feedback">
        <div>
          <div>{{ item.view }}</div>
          <div>{{ item.createByName}}  {{ item.createTime }}</div>
        </div>
    </el-form-item>
    <el-form-item label="办理意见" prop="feedback">
      <el-input type="textarea" v-model="detailform.feedback" placeholder="请输入办理意见" />
    </el-form-item>

    </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button  @click="submitcancel">取 消</el-button>
          <el-button  type="primary" @click="submitfeedForm">反馈</el-button>
          <el-button  type="primary" @click="submitdoForm">办结</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增修改分类目录 -->
    <el-dialog :title="updateTypeDialog.title" v-model="updateTypeDialog.visible" width="500px" append-to-body>
      <el-form :model="updatetypeForm" ref="updateTypeRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="类型名称" prop="typeName">
            <el-input v-model="updatetypeForm.typeName"  placeholder="请输入名称" clearable style="width: 240px"  />
          </el-form-item>
          <el-form-item label="父级分类" prop="parentId">
            <el-select v-model="updatetypeForm.parentId" placeholder="请选择">
    <el-option
      v-for="item in groupOptions"
      :key="item.typeId"
      :label="item.typeName"
      :value="item.typeId">
    </el-option>
  </el-select>
          </el-form-item>
        </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="TypesubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Group" lang="ts">
import { getGroup, delGroup, addGroup, updateGroup, groupTreeSelect } from '@/api/attendance/setting/group';
import { GroupVO, GroupQuery, GroupForm } from '@/api/attendance/setting/group/types';
import { DeptVO } from '@/api/system/dept/types';
import { listClassInfo } from '@/api/office/class';
import api from '@/api/system/user';
import {
  studentTree,
  attendanceGroupPage as attendanceGroupStudentPage,
  editAttendanceGroup as editStudentAttendanceGroup,
  removeAttendanceGroup as removeStudentAttendanceGroup
} from '@/api/office/student';
import {
  attendanceGroupPage as attendanceGroupStaffPage,
  editAttendanceGroup as editStaffAttendanceGroup,
  removeAttendanceGroup as removeStaffAttendanceGroup
} from '@/api/office/staff';
import { addinspectItems, addinspecttask, addtasktype, deleteinspectItems, deleteinspectItemsCatalogue, deleteinspecttask, deletetasktype, inspectItemsCatalogue, inspectioninspectItemsdetail, inspectioninspectItemslist, inspecttasklist, searchinspectItemsCatalogue, searchspecttaskdetail, searchtasktypelist, updateinspectItems, updateinspectItemsCatalogue, updateinspecttask, updatetasktype, userlist } from '@/api/inspection';
import { StudentRecognitionRecordForm } from '@/api/attendance/recognize/student/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { student_accommodation_type, school_post } = toRefs<any>(proxy?.useDict('student_accommodation_type', 'school_post'));
const groupList = ref<any[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const studentRecognitionRecordFormRef = ref<ElFormInstance>();
const ddetailRecordFormRef = ref<ElFormInstance>();
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const groupOptions = ref<any[]>([
  // {
  //         typeName: '全部',
  //         typeId:"全部",
  //         children: []
  //       }
]);

//任务状态 全部、处理中、已取消、已完成、超时待办
const taskStausArr=ref<any[]>([
  {
    id:"",
    label: "全部"
  },
  {
    id:"0",
    label: "处理中"
  },
  {
    id:"1",
    label: "已取消"
  },
  {
    id:"2",
    label: "已完成"
  },
  {
    id:"3",
    label: "超时待办"
  },
])
const timeTypeonchange=(e:any,c:any)=>{
  let startTime = new Date();
  let endTime = new Date();
  startTime.setHours(0, 0, 0, 0); 
  if(queryParams.value.belongId=="1"){
    startTime.setDate(startTime.getDate())
  }if(queryParams.value.belongId=="2"){
    startTime.setDate(startTime.getDate() - 1);
  }if(queryParams.value.belongId=="3"){
    startTime.setMonth( startTime.getMonth());
    startTime.setDate(1)
  }if(queryParams.value.belongId=="4"){
    startTime.setMonth( startTime.getMonth()-1);
    startTime.setDate(1);
    endTime.setMonth(endTime.getMonth());
    endTime.setDate(0)
    endTime.setHours(23, 59, 59, 999);
  }if(queryParams.value.belongId=="5"){
    let day=startTime.getDay()
    startTime.setDate(startTime.getDate()-day+(day === 0 ? -6 : 1));
  }if(queryParams.value.belongId=="6"){
    let day=startTime.getDay();
    startTime.setDate(startTime.getDate()-day-7+(day === 0 ? -6 : 1));
    endTime.setDate(endTime.getDate()-day-1+(day === 0 ? -6 : 1));
    endTime.setHours(23, 59, 59, 999);
  }if(queryParams.value.belongId=="7"){
    startTime.setDate(startTime.getDate() - 7);
  }if(queryParams.value.belongId=="8"){
    startTime.setDate(startTime.getDate() - 30);
  }if(queryParams.value.belongId=="9"){
    startTime.setFullYear(startTime.getFullYear()-1);
  }if(queryParams.value.belongId=="10"){
    startTime.setMonth(0);
    startTime.setDate(1)
  }if(queryParams.value.belongId=="11"){
    startTime.setFullYear(startTime.getFullYear()-1);
    startTime.setMonth(0);
    startTime.setDate(1);
    endTime.setFullYear(endTime.getFullYear()-1);
    endTime.setMonth(11);
    endTime.setDate(31);
    endTime.setHours(23, 59, 59, 999);
  }else{
    startTime.setDate(startTime.getDate())
  }
  dateRangeCreateTime.value = [proxy?.parseTime(startTime, '{y}-{m}-{d} {h}:{i}:{s}'), proxy?.parseTime(endTime, '{y}-{m}-{d} {h}:{i}:{s}')];

}
const formGroupOptions = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const groupFormRef = ref<ElFormInstance>();
const groupLinkFormRef = ref<ElFormInstance>();
const crewLinkFormRef = ref<ElFormInstance>();
const groupType = ref('1');
const deptOptions = ref<DeptVO[]>([]);
const activeName= ref('0')
const num=ref(1)
//新增修改分类目录ref
const updateTypeRef = ref<ElFormInstance>();
const passArr = ref<any[]>([
  {
    id:"1",
    label: "始终合格"
  },
  {
    id:"2",
    label: "始终不合格"
  },
  {
    id:"3",
    label: "无内容合格"
  },
  {
    id:"4",
    label: "有内容合格"
  },
  {
    id:"5",
    label: "默认始终合格"
  },
]);
const isScoreArr=ref<any[]>([
  {
    id:"0",
    label: "否"
  },
  {
    id:"1",
    label: "是"
  },
]);

//选择项
const chargeForm=ref<any>({
  itemsName:"",
  catalogueId:"",
  xzIsChoice:0,
  isRequired:0,
  remark:""
})
//数字项
const numForm=ref<any>({
  itemsName:"",
  catalogueId:"",
  isRequired:0,
  numUnit:undefined,
  numInputUpperLimit:0,
  numInputLowerLimit:0,
  numPassUpperLimit:0,
  numPassLowerLimit:0,
  numPassScore:0,
  numPassNoScore:0,
  txtDefaultValue:0,
  remark:""
});
//文本项
const textForm=ref<any>({
  itemsName:"",
  catalogueId:"",
  isRequired:0,
  txtPassJudge:"",
  numPassScore:0,
  numPassNoScore:0,
  txtDefaultValue:"",
  remark:""
});
const numFormRef = ref<ElFormInstance>();
const textFormRef = ref<ElFormInstance>();
// const classOptions = ref<any[]>([]);
  const classOptions = ref<any[]>([
  {
    id:"1",
    label: "今天"
  },
  {
    id:"2",
    label: "昨天"
  },
  {
    id:"3",
    label: "本月"
  },
  {
    id:"4",
    label: "上月"
  },
  {
    id:"5",
    label: "本周"
  },
  {
    id:"6",
    label: "上周"
  },
  {
    id:"7",
    label: "最近7天"
  },
  {
    id:"8",
    label: "最近30天"
  },
  {
    id:"9",
    label: "最近12月"
  },
  {
    id:"10",
    label: "今年"
  },
  {
    id:"11",
    label: "去年"
  },
  {
    id:"12",
    label: "全部"
  },
]);
const showMenu = ref(false);
const currentNodeData = ref<any>({});
const treeTransferRef = ref(); // 树形穿梭框
const fromData = ref([]); // 树形数据
const toData = ref([]); // 选中的ids数据
const transferProps = ref({ value: 'id', label: 'label', children: 'children', disabled: 'disabled', pid: 'parentId' });
const attendanceMemberIds = ref<any[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
//巡检任务详情
const detaildialog= reactive<DialogOption>({
  visible: false,
  title: ''
});
const groupLinkDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const crewLinkDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
//分类目录新增修改
const UpdateTypeDialogShow = () => {
  reset();
  updatetypeForm.value.parentId=""
  delete updatetypeForm.value.catalogueId
  // updatetypeForm.value.catalogueId=""
  updatetypeForm.value.typeName=""
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改/新增分类目录';
};
//新增修改分类目录弹窗
const updateTypeDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const updatetypeForm= ref<any>({
  typeName:undefined,
  parentId:"0"
})
const imageUrl=ref<any>("")
const handleClick=(e,c)=>{
  // console.log("eee",e,c)

}
/**分类新增提交按钮 */
const TypesubmitForm = () => {
  updateTypeRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      console.log("dddddd",updatetypeForm.value)
      if(!updatetypeForm.value.parentId){
          updatetypeForm.value.parentId="0"
      }
      // if (updatetypeForm.value?.catalogueId!==undefined) {
      //   await updatetasktype(updatetypeForm.value).finally(() => (buttonLoading.value = false));
      // } else {
        await addtasktype(updatetypeForm.value).finally(() => (buttonLoading.value = false));
      // }
      proxy?.$modal.msgSuccess('修改成功');
      updateTypeDialog.visible = false;
      await getGroupTree();
    }
  });
};
const initFormData: any = {
  taskName:"",
  executor:"",
  typeId:"",
  askCompleteTime:"",
  remark:"",
  imgList:"",
  taskStatus:"",
  createByName:""
};
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // studentName: undefined,
    classId: undefined,
    gradeLevel: undefined,
    studentStatus: undefined,
    deviceType: undefined,
    itemsName:undefined,
    catalogueId:undefined,
    params: {
      recognizeTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生id不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'change' }],
    classId: [{ required: true, message: '班级id不能为空', trigger: 'blur' }],
    gradeLevel: [{ required: true, message: '级别不能为空', trigger: 'change' }],
    studentStatus: [{ required: true, message: '学生状态不能为空', trigger: 'change' }],
    recognizeTime: [{ required: true, message: '识别时间不能为空', trigger: 'blur' }],
    deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
    deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    facePic: [{ required: true, message: '图片路径不能为空', trigger: 'blur' }],
    snapshotPic: [{ required: true, message: '抓拍图不能为空', trigger: 'blur' }],
    comparisonScore: [{ required: true, message: '比对分值不能为空', trigger: 'blur' }],

    itemsName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    // txtPassJudge: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    // catalogueId: [{ required: true, message: '学生id不能为空', trigger: 'blur' }],
  }
});

const { queryParams, form, rules } = toRefs(data);

const linkForm = ref<any>({});

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  if (100 === data.id) {
    return;
  }
  form.value.parentId = data.id;
  getGroup(data.id).then((resp) => {
    groupType.value = resp.data.groupType;
    const groupIds = [...resp.data.children];
    groupIds.push(data.id);
    queryParams.value.attendanceGroupIds = groupIds;
    handleQuery();
  });
};

/** 查询部门下拉树结构 */
const getGroupTree = async () => {
  const res:any = await searchtasktypelist();
  console.log("ddddddd",res)
  groupOptions.value = res.data;
  // groupOptions.value[0].children = res.rows;
};

const searchClassInfo = (queryString, cb) => {
  listClassInfo({ className: queryString }).then((response) => {
    cb(response.rows);
  });
};

/** 查询部门下拉树结构 */
const getDeptTree = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

const openContextMenu = (event: any, nodeData: any) => {
  // 设置菜单的位置
  const menu = proxy?.$el.querySelector('.custom-menu');
  const clickX = event.clientX;
  const clickY = event.clientY;
  menu.style.left = clickX + 10 + 'px';
  menu.style.top = clickY + 'px';
  currentNodeData.value = nodeData;
  if(currentNodeData.value.typeId!=="全部"){
    showMenu.value = true;
  }
  // showMenu.value = true;
};

const menuItemAdd = (option: any) => {
  // showMenu.value = false;
  // handleAdd();
  console.log("ddddd",option)
  updatetypeForm.value.parentId=""
  updatetypeForm.value.catalogueId=""
  updatetypeForm.value.catalogueName=""
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改/新增分类目录';
};

const menuItemUpdate = (option: any) => {
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改/新增分类目录';
  console.log("currentNodeData",currentNodeData)
  reset();
  Object.assign(updatetypeForm.value, currentNodeData.value);
  console.log("ddddd",updatetypeForm)
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改分类目录';
};

const menuItemLink = (option: any) => {
  showMenu.value = false;
  handleAddLink(currentNodeData.value);
};

const menuItemDelete = async () => {
  showMenu.value = false;
  console.log("currentNodeData",currentNodeData?.value),
  await deletetasktype(currentNodeData?.value?.typeId);
  proxy?.$modal.msgSuccess('删除成功');
      updateTypeDialog.visible = false;
      await getGroupTree();
};

const menuHide = (option: any) => {
  showMenu.value = false;
};

/** 查询考勤分组列表 */
const getList = async () => {
  loading.value = true;
  // queryParams.value.params = {};
  console.log("ddddddddddd",queryParams.value.params)
  // proxy?.addDateRange(queryParams.value, dateRangeRecognizeTime.value, 'PunchTime');
  const res = await inspecttasklist(queryParams.value);
  groupList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const todolist=ref<any>([])
/** 查询执行人列表 */
const gettodoList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  // proxy?.addDateRange(queryParams.value, dateRangeRecognizeTime.value, 'PunchTime');
  const res = await userlist({});
  todolist.value = res.rows;
  // total.value = res.total;
  loading.value = false;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

const cancelLink = () => {
  reset();
  groupLinkDialog.visible = false;
  crewLinkDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  fromData.value = [];
  toData.value = [];
  linkForm.value = {};
  treeTransferRef.value?.clearData();
  groupFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.taskId );
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(":dddddd",selection)
};

const loadFromData = async () => {
  if (groupType.value === '1') {
    const res = await studentTree();
    fromData.value = res.data;
  } else if (groupType.value === '2') {
    const res = await api.deptUserTreeSelect();
    fromData.value = res.data;
  }
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  numForm.value={};
  textForm.value={}
  // form.value.parentId = groupType.value === '1' ? 101 : 102;
  await loadFromData();
  treeTransferRef.value?.initData();
  dialog.visible = true;
  dialog.title = '新增';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GroupVO) => {
  reset();
  await loadFromData();
  treeTransferRef.value?.initData();
  const _groupId = row?.id || ids.value[0];
  const res = await getGroup(_groupId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改考勤分组';
};
const detailform=ref<any>({
  taskName:"",
  executor:"",
  createByName:"",
  remark:"",
  taskImgs:[],
  feedback:"",
  isButton:"",

})
const handleUpdateGroup = async (row?: any) => {
  detaildialog.visible = true;
  detaildialog.title = '明细/反馈/办结';
  reset();
    let res=await searchspecttaskdetail(row?.taskId);
    detailform.value=res.data;
    let arr:any=[]
    console.log("rerere",res)
    res?.data?.taskImgs?.map((item:any)=>{
         arr.push(item?.taskImgAddress)
      });
    detailform.value.imgList=arr;
    console.log("detailform",detailform.value)
};

const handleAddLink = async (row: any) => {
  reset();
  await loadFromData();
  treeTransferRef.value?.initData();
  linkForm.value.groupId = row.id;
  groupLinkDialog.visible = true;
  groupLinkDialog.title = '关联考勤人员';
};
const newDate=(time:any)=> {
  var date = new Date(time);
            var y = date.getFullYear();
            var m:any = date.getMonth() + 1;
            m = m < 10 ? ('0' + m) : m;
            var d:any = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            var h = date.getHours();
            var minute:any = date.getMinutes();
            minute = minute < 10 ? ('0' + minute) : minute;
            var second:any = date.getSeconds();
            second = second < 10 ? ('0' + second) : second;
            return y + '-' + m + '-' + d+' '+h+':'+minute+ ':' + second;
    }

/** 提交按钮 */
const submitForm =  () => {
  // numForm.value.itemsType=activeName.value
  console.log("Ffffff",form.value)
  studentRecognitionRecordFormRef.value?.validate(async(valid:boolean)=>{
     if(valid){
      let staffArr:any=[];
      console.log("totott",todolist)
      form.value.executor?.map((it:any)=>{
        todolist?.value?.map((i:any)=>{
          if(it==i.nickName){
            staffArr.push({staffId:i.userId})
          }
        })
      })
      let arr:any=[];
      form.value?.imgList?.map((item:any)=>{
         arr.push({
          taskImgAddress:item
         })
      });
      let obj=Object.assign({},form.value);
      obj.executor=form.value.executor.toString();
      obj.staffList=staffArr
      obj.imgList=arr
      obj.askCompleteTime=newDate(obj.askCompleteTime)
      // form.value.imgList=arr
      console.log("foffff",form.value,obj)
      await addinspecttask(obj).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('新增成功');
      dialog.visible = false;
      await getList();
     }
  })
};
//取消
const submitcancel=()=>{
  console.log("ddddddeada",detailform)
  buttonLoading.value = true;
  ddetailRecordFormRef.value?.validate(async(valid:boolean)=>{
    if(valid){
      await updateinspecttask({taskId:detailform?.value.taskId,isButton:"1",feedback:detailform?.value.feedback});
      proxy?.$modal.msgSuccess('取消成功');
      detaildialog.visible=false;
      buttonLoading.value = false;
      await getList();
    }
  })
}
//反馈
const submitfeedForm=()=>{
  buttonLoading.value = true;
  ddetailRecordFormRef.value?.validate(async(valid:boolean)=>{
    if(valid){
      await updateinspecttask({taskId:detailform?.value.taskId,isButton:"0",feedback:detailform?.value.feedback});
      proxy?.$modal.msgSuccess('反馈成功');
      detaildialog.visible=false;
      buttonLoading.value = false;
      await getList();
    }
  })
}
//办结
const submitdoForm=()=>{
  buttonLoading.value = true;
  ddetailRecordFormRef.value?.validate(async(valid:boolean)=>{
    if(valid){
      await updateinspecttask({taskId:detailform?.value.taskId,isButton:"2",feedback:detailform?.value.feedback});
      proxy?.$modal.msgSuccess('办结成功');
      detaildialog.visible=false;
      buttonLoading.value = false;
      await getList();
    }
  })
}
const submitGroupLinkForm = () => {
  buttonLoading.value = true;
  if (groupType.value === '1') {
    linkForm.value.studentIds = attendanceMemberIds.value;
    editStudentAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  } else {
    linkForm.value.staffIds = attendanceMemberIds.value;
    editStaffAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  }
  proxy?.$modal.msgSuccess('修改成功');
  groupLinkDialog.visible = false;
  getList();
};

const submitCrewLinkForm = () => {
  buttonLoading.value = true;
  if (groupType.value === '1') {
    editStudentAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  } else {
    editStaffAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  }
  proxy?.$modal.msgSuccess('修改成功');
  crewLinkDialog.visible = false;
  getList();
};

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  console.log("handddd",row)
  if(!row){
  await proxy?.$modal.confirm('是否确认删除"' + ids.value.length + '"条数据？').finally(() => (loading.value = false));
  await deleteinspecttask(ids.value);
  proxy?.$modal.msgSuccess('删除成功');
  }else{
    const _groupIds = row.taskId;
  await proxy?.$modal.confirm('是否确认删除巡检任务"' + row.taskName + '"？').finally(() => (loading.value = false));
  await deleteinspecttask(_groupIds);
  proxy?.$modal.msgSuccess('删除成功');
  }
  await getGroupTree();
};

const handleRemoveFromGroup = async (row?: any) => {
  const _ids = row?.itemsId ;
  let msg = groupList.value.find((e) => _ids === e.itemsId).itemsName;
    await proxy?.$modal.confirm('是否确认删除"' + msg + '"的数据项？').finally(() => (loading.value = false));
    await deleteinspectItems(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
      'inspection/task/export' ,
    {
      ...queryParams.value
    },
    `task_${new Date().getTime()}.xlsx`
  );
};

/**
 * 将选中菜单存入表单
 * @param val 子组件穿梭框返回
 */
const checkVal = (val: any) => {
  const arr = [];
  for (const i of val) {
    if (!i.children) {
      arr.push(i.id);
    }
  }
  attendanceMemberIds.value = arr;
};

onMounted(() => {
  getDeptTree();
  getGroupTree();
  getList();
  gettodoList()
});
</script>
<style lang="scss" scoped>
@import '@/assets/styles/variables.module';
.custom-menu {
  position: fixed;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  z-index: 1000;
}

.custom-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.custom-menu ul li {
  padding: 8px 20px;
  cursor: pointer;
  font-size: 13px;
  color: $blue;
}

.custom-menu ul li:hover {
  background-color: #eee;
}
.ss-tabs {
  background-color: #fff;
}

</style>
